import { ElMessage, ElLoading } from "element-plus";
// 引入code码 文件
import errorCode from "./errorCode";
// 引入自定义请求库
import { postAction } from "@/utils/system/commonUse";

/**
 *  验证是否为blob格式
 */
export async function blobValidate(data: any) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
/**
 * 下载文件
 * @param {地址} hrefUrl
 * @param {文件名} fileName
 */
export async function downloadFile(hrefUrl: string, fileName: string) {
  let a = document.createElement("a");
  a.href = hrefUrl;
  a.download = fileName; // 下载后文件名
  document.body.appendChild(a);
  a.click(); // 点击下载
  document.body.removeChild(a); // 下载完成移除元素
}

/**
 * @description:通用下载方法
 * @param {请求地址} url
 * @param {请求参数} params
 * @param {文件名} filename
 * @param {回掉函数} callback
 * @returns
 */
export function download(
  url: string,
  data: any,
  filename: string,
  callback?: Function
) {
  let downloadLoadingInstance = null as any;
  try {
    console.log(url, data, filename, callback);
    downloadLoadingInstance = ElLoading.service({
      text: "正在下载数据，请稍候",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });

    return postAction(url, data, {
      //   headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
    })
      .then(async (data: any) => {
        console.log("data====>", data);
        const isLogin = await blobValidate(data);
        if (isLogin) {
          //   const blob = new Blob([data]);
          const url = window.URL.createObjectURL(data);
          downloadFile(url, filename);
          //   saveAs(blob, filename);
        } else {
          const resText = await data.text();
          console.log("resText===>", resText);
          const rspObj = JSON.parse(resText);
          const errMsg =
            errorCode[rspObj.code as keyof typeof errorCode] ||
            rspObj.msg ||
            errorCode["default"];
          ElMessage.error(errMsg);
        }
        downloadLoadingInstance.close();
      })
      .catch(async (r) => {
        console.log(r);
        ElMessage.error("下载文件出现错误，请联系管理员！");
        downloadLoadingInstance.close();
      });
  } catch (error) {
    console.log("error", error);
  } finally {
    // 判断是否是 函数
    callback && callback();
  }
}
